package com.akuhome.resource.service.check;

import com.akuhome.resource.DO.check.FoodCheck;
import com.akuhome.resource.DO.check.use.FoodActual;
import com.akuhome.resource.dao.CheckDao;
import com.akuhome.resource.dto.check.FoodCheckInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
public class FoodCheckService {
    @Autowired
    CheckDao checkDao;
    public FoodCheckInfo findFoodCheckInfoByProjectId(Integer pid){
        return checkDao.findFoodCheckInfoByProjectId(pid);
    }

    public void updateFoodCheckInfo(FoodCheckInfo info){
        checkDao.updateFoodCheck(info.getFoodCheck());
        updateFoodActualList(info.getActualList(),info.getFoodCheck().getId());
    }

    @Transactional(rollbackFor = {RuntimeException.class,Exception.class, SQLException.class})
    public void updateFoodActualList(List<FoodActual> actualList,Integer checkId){
        List<FoodActual> oldList = checkDao.findFoodActualByFoodCheckId(checkId);
        List<FoodActual> deleteList = new ArrayList<>(oldList);
        List<FoodActual> insertList = actualList;
        deleteList.removeAll(insertList);
        insertList.removeAll(oldList);
        if(insertList.size()>0)
            checkDao.updateFoodActualList(insertList);
        if(deleteList.size()>0)
            checkDao.deleteFoodActualList(deleteList);
    }

    public Integer insertFoodCheck(FoodCheck foodCheck,String uid){
        checkDao.insertFoodCheck(foodCheck,uid);
        return foodCheck.getId();
    }

    public void insertFoodActual(List<FoodActual> foodActual){
        checkDao.insertFoodActualList(foodActual);
    }

}
